package com.cumt.threeway.view.dialog;

import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.cumt.threeway.R;
import com.cumt.threeway.activity.LoginActivity;
import com.cumt.threeway.constant.ThreeWayConstant;
import com.cumt.threeway.constant.URLS;
import com.cumt.threeway.util.ThreeWayData;
import com.cumt.threeway.util.ThreeWayUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jingjing.Hu on 2016/4/22.
 */
public class ResetPswFinishDialog extends DialogFragment implements View.OnClickListener {

    private Button mButtonBack = null;
    private Button mButtonFinish= null;
    private EditText mEditTextPassword = null;
    private EditText mEditTextConfirmPassword = null;
    private Context mContext = null;
    private long mCurrentTime = 0;

    private Button mDelView1 = null;
    private Button mDelView2 = null;

    private int mCount = 0;

    private static String mPhoneNum = null;

    private final int LOGIN_CONFIRMPASSWORD =2;
    private final int LOGIN_PASSWORD = 1;
    private final int REGISTER_ENABLED = 3;
    private RequestQueue queue;

    private Handler mHandler = new Handler();

    public static ResetPswFinishDialog newInstance(String name) {
        mPhoneNum = name;
        return new ResetPswFinishDialog();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int styleNormal = android.support.v4.app.DialogFragment.STYLE_NORMAL;
        int theme = android.R.style.Theme_Light_NoTitleBar_Fullscreen;
        setStyle(styleNormal, theme);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_reset_finish_layout, null, false);
        initView(view);
        setListener();
        return view;
    }

    private void initView(View view) {
        queue = Volley.newRequestQueue(mContext);
        mButtonBack = (Button) view.findViewById(R.id.btn_back);
        mButtonFinish = (Button) view.findViewById(R.id.btn_finish);
        mEditTextPassword = (EditText) view.findViewById(R.id.et_psw);
        mEditTextConfirmPassword = (EditText) view.findViewById(R.id.et_confirm_psw);
        mDelView1 = (Button) view.findViewById(R.id.btn_del1);
        mDelView2 = (Button) view.findViewById(R.id.btn_del2);
        mButtonFinish.setAlpha(0.4f);
    }

    private void setListener() {
        mDelView1.setOnClickListener(this);
        mDelView2.setOnClickListener(this);
        mButtonBack.setOnClickListener(this);
        mButtonFinish.setOnClickListener(this);
        mEditTextPassword.addTextChangedListener(new TextChangedListener(LOGIN_PASSWORD));
        mEditTextConfirmPassword.addTextChangedListener(new TextChangedListener(LOGIN_CONFIRMPASSWORD));
    }

    private class TextChangedListener implements TextWatcher {

        private int mType = 0;

        public TextChangedListener(int type) {
            mType = type;
        }

        @Override
        public void afterTextChanged(Editable editable) {
            if (mCount == REGISTER_ENABLED) {
                mButtonFinish.setEnabled(true);
                mButtonFinish.setAlpha(0.8f);
            } else {
                mButtonFinish.setEnabled(false);
                mButtonFinish.setAlpha(0.4f);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int start,int count, int end) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start,int count, int end) {
            switch (mType) {
                case LOGIN_CONFIRMPASSWORD:
                    if (!TextUtils.isEmpty(charSequence)) {
                        mDelView2.setVisibility(View.VISIBLE);
                        mCount |= LOGIN_CONFIRMPASSWORD;
                    } else {
                        if ((mCount & LOGIN_CONFIRMPASSWORD) == LOGIN_CONFIRMPASSWORD) {
                            mCount -= LOGIN_CONFIRMPASSWORD;
                        }
                    }
                    break;
                case LOGIN_PASSWORD:
                    if (!TextUtils.isEmpty(charSequence)) {
                        mDelView1.setVisibility(View.VISIBLE);
                        mCount |= LOGIN_PASSWORD;
                    } else {
                        if ((mCount & LOGIN_PASSWORD) == 1) {
                            mCount -= LOGIN_PASSWORD;
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View view) {
        if (view == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_del1:
                mEditTextPassword.setText("");
                mDelView1.setVisibility(View.INVISIBLE);
                break;
            case R.id.btn_del2:
                mEditTextConfirmPassword.setText("");
                mDelView2.setVisibility(View.INVISIBLE);
                break;
            case R.id.btn_back:
                dismiss();
                break;
            case R.id.btn_finish:
                if (!getEditContent(mEditTextPassword).equals(getEditContent(mEditTextConfirmPassword))) {
                    ThreeWayUtil.getInstance().showToast(mContext, mContext.getResources().getString(R.string.password_not_same));
                } else {
//                    submitPasswordToServer();
                    ThreeWayData.getInstance().updateUserPassword(getEditContent(mEditTextPassword));
                    ThreeWayUtil.getInstance().showToast(mContext, getResources().getString(R.string.edit_success));
                }
                break;
            default:
                break;
        }
    }

    private void goLoginActivity() {
        dismiss();
        Intent intent = new Intent(mContext, LoginActivity.class);
        intent.putExtra("key", ThreeWayConstant.REQUEST_CODE_FOR_LOGIN);
        startActivity(intent);
    }

    private String getEditContent(EditText editText) {
        return editText.getText().toString();
    }

    private void submitPasswordToServer() {
        StringRequest srPost = new StringRequest(Request.Method.POST, URLS.IP + "NetServlet/UpdateRegistData",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String userRegister = response.toString();
                        if (("true\r\n").equals(userRegister)) {
                            ThreeWayUtil.getInstance().showToast(mContext, getResources().getString(R.string.edit_success));
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    goLoginActivity();
                                }
                            }, 1000);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            // 当手机发送请求时，回调用getParams方法，拼请求
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("telephone", mPhoneNum);
                map.put("password", getEditContent(mEditTextPassword));
                return map;
            }
        };
        queue.add(srPost);
    }
}
